package com.tiantian.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;

import com.html5.PlayApplication;
import com.music.model.Music;

public class PlayerService extends Service {
	private MediaPlayer mediaPlayer=null;
	private Music music=null;
	private static final int PLAYING=0;
	private static final int PAUSE=1;
	private static final int JUMP=2;
	private PlayApplication app=null;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		app=(PlayApplication)this.getApplicationContext();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		int msg=intent.getIntExtra("msg",0);
		if(msg==PLAYING)
		{
			if(music==null)
			{
			 music=(Music)intent.getSerializableExtra("music");
			 Uri uri=Uri.parse(music.getMusicUrl());
				mediaPlayer=MediaPlayer.create(this, uri);
				mediaPlayer.setLooping(true);
			}
			playMusic();
		}else if(msg==PAUSE)
		{
			pauseMusic();
		}else if(msg==JUMP)
		{
			if(mediaPlayer!=null)
			{
				mediaPlayer.stop();
				mediaPlayer.release();
				mediaPlayer=null;
			}
			
			 music=(Music)intent.getSerializableExtra("music");
			 Uri uri=Uri.parse(music.getMusicUrl());
				mediaPlayer=MediaPlayer.create(this, uri);
				mediaPlayer.setLooping(false);
			playMusic();
		}
		return super.onStartCommand(intent, flags, startId);
	}

	

	//播放
	public void playMusic()
	{
		if(mediaPlayer!=null)
		{
		   mediaPlayer.start();
	        new Thread(new PlayProgress()).start();
		}
	}
	//暂停
	public void pauseMusic()
	{
		if(mediaPlayer!=null)
		{
			mediaPlayer.pause();
		}
	}
	public class PlayProgress implements Runnable{
		boolean flag=true;
		@Override
		public void run() {
			while(flag)
			{
				app.setCurrentPosition(mediaPlayer.getCurrentPosition());
				app.setDuration(mediaPlayer.getDuration());
				app.setPlaying(mediaPlayer.isPlaying());
			      if(!mediaPlayer.isPlaying())
			      {
			    	  flag=false;
			      }
			      try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			    
		}
	}
}
